package org.ezplatform.office.forum.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.transaction.Transactional;

import org.ezplatform.cloud.common.log.LogService;
import org.ezplatform.core.dao.jpa.JpaBaseDao;
import org.ezplatform.core.pagination.PropertyFilter;
import org.ezplatform.core.service.BaseService;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.office.forum.dao.ForumLabelDao;
import org.ezplatform.office.forum.dao.ForumModeratorScorpDao;
import org.ezplatform.office.forum.dao.ForumPostLabelDao;
import org.ezplatform.office.forum.entity.ForumLabel;
import org.ezplatform.office.forum.entity.ForumModeratorScope;
import org.ezplatform.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

/**
 * @desc 论坛标签service
 * @create 2017-11-15 19:53
 **/
@Service
@Transactional
public class ForumLabelService extends BaseService<ForumLabel, String> {

    private final Logger LOGGER = LoggerFactory.getLogger(ForumLabelService.class);

    @Autowired
    private ForumLabelDao forumLabelDao;

    @Autowired
    private ForumPostLabelDao forumPostLabelDao;
    
    @Autowired
    private ForumModeratorScorpDao forumModeratorScorpDao;

    @Autowired
	private LogService logService;
    
    @Override
    protected JpaBaseDao<ForumLabel, String> getEntityDao() {
        return forumLabelDao;
    }
    
    public List<Map> findAllLabels(String corpId) {
		String sql = " select id,name,color,status from oa_forum_label where corp_id = :corpId and status = 1 and is_delete = 0 order by createdDate desc ";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("corpId", corpId);
		return super.findByListNativeQuery(sql, null, paramMap);
	}

    /**
     * 
     * @Title: findAllLabel
     * @Description:
     *     根据corpId获取所有的标签
     * @param corpId
     * @return 
     * @return: List<Map>
     *
     * @date 2017年11月24日 下午6:41:08
     *
     */
	public List<Map> findAllLabel(String corpId) {
		String sql = " select id,name,color,status from oa_forum_label where corp_id = :corpId and status = 1 and is_delete = 0 order by  sort_no,createdDate desc,name desc ";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("corpId", corpId);
		return super.findByListNativeQuery(sql, null, paramMap);
	}
	
	//查看当前人是不是版主还是发帖人---并且必须和相应的板块挂钩
	public List<ForumModeratorScope> selectAllModerator(String userId,String boardId,String userName) {
		  List<ForumModeratorScope> demoUser = forumModeratorScorpDao.findForumModeratorScorp(userId,boardId);
		 return  demoUser;
	}


    /**
     *
     * @Title: findPage
     * @Description:
     *     分页获取
     * @param pageable
     * @param filter
     * @param corpId
     * @return
     * @return: List<Map>
     *
     * @date 2017年11月24日 下午6:41:08
     *
     */
    public Page<Map> findPage(Pageable pageable, List<PropertyFilter> filter, String token, String corpId) {
        StringBuffer sql = new StringBuffer();
        Map<String, Object> values = new HashMap<String, Object>();
        sql.append(" select a.id, a.name, a.createdDate, a.createdBy, a.createdName, a.color, a.sortNo, a.status,a.isInit  from ( ");
        sql.append(" select l.id, l.name, l.createdDate, l.createdBy, x.userName as createdName, l.color, l.sort_no as sortNo, l.status,l.is_init as isInit");
        sql.append(" from oa_forum_label l ");
        sql.append(" left join  ");
        sql.append(" (select u.id, u.user_name as userName from sys_user u where  u.corp_id = :corpId ");
        //sql.append(" u.is_delete = 0 and ");
        sql.append(" union select a.id, a.trueName as userName from sys_admin a where a.corp_id = :corpId) x ");
        sql.append(" on x.id = l.createdBy ");
        sql.append(" where l.corp_id = :corpId and l.is_delete = 0");
        sql.append(" ) a where 1 = 1 ");
        values.put("corpId", corpId);
        String s = sql.toString();
        s = PropertyFilter.getSqlByFilterAndPageable("a", s, " a.sortNo,a.createdDate desc, a.name desc ", filter, pageable);
        Page<Map> page = super.findByPageNativeSQL(pageable, s, values);
        return page;
    }


    /**
     *
     * @Title: logicDelete
     * @Description:
     *     逻辑删除信息
     * @param ids
     *
     * @return: boolean
     *
     * @date 2017年12月7日 下午12:36:37
     *
     */
    public OperationResult logicDelete(String[] ids) {
        LOGGER.info("开始删除论坛标签信息");
        List<String> idList = Arrays.asList(ids);
        List<ForumLabel> list = forumLabelDao.getLabel(idList);
        forumLabelDao.setLabelDel(1, idList);
        for (ForumLabel forumLabel : list) {
        	logService.saveModuleLog("forum:label:04", forumLabel.getName(), ""); 
		}
        return OperationResult.buildSuccessResult("删除成功");
    }

    /**
     * 移动端获取标签，根据当前主题查询已经有哪些标签
     * @param id
     * @param corpId
     * @return
     */
    public List<Map> getAllLabelById(String postId,String corpId) {
    	List<Map> list = new ArrayList<Map>();
		//查询所有的标签
		List<ForumLabel> labelList = forumLabelDao.getCorpLable(corpId);
		//根据主题帖去查询标签
		if(labelList != null && !labelList.isEmpty()) {
			 List<String> result = forumPostLabelDao.getLabelIdByPost(postId);
			 /*if (result != null && !result.isEmpty()) {*/
				 for (ForumLabel fl : labelList) {
					 Map map = new HashMap();
					 map.put("id", fl.getId());
					 map.put("name", fl.getName());
					 boolean checked=false;
					 if(result.contains(fl.getId())){
						 checked=true;
					 }
					 map.put("checked", checked);
					 list.add(map);
				}
			/*}*/
		 }
		 return list;
    }


	public boolean checkLabel(String name, String corpId, String id) {
		List<ForumLabel> list = forumLabelDao.checkLabel(name,corpId);
		if(StringUtils.isNotBlank(id)) {
			if(list.size()>0&&!id.equals(list.get(0).getId())) {
				return true;
			}else {
				return false;
			}
		}else {
			if(list.size()>0) {
				return true;
			}else {
				return false;
			}
		}
		
		// TODO Auto-generated method stub
		
	}
}
